package com.ingdan.contactdemo;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.SectionIndexer;
import android.widget.TextView;

import java.util.List;


@SuppressLint("NewApi")
public class ContactAdapter extends BaseAdapter implements SectionIndexer {

    private Context mContext;
    private final LayoutInflater mInflater;
    List<Person> newsList;//定义的新闻列表集合

    public ContactAdapter(Context mContext, List<Person> newsList) {
        this.mContext = mContext;
        this.newsList = newsList;
        mInflater = LayoutInflater.from(mContext);
    }

    /**
     * 当ListView数据发生变化时,调用此方法来更新ListView
     *
     * @param list
     */
    public void updateListView(List<Person> list) {
        this.newsList = list;
        notifyDataSetChanged();
    }
    @Override
    public int getCount() {
        return newsList.size();
    }

    @Override
    public Object getItem(int position) {
        return newsList.get(position);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    //listView每一行要显示的内容
    @Override
    public View getView(final int position, View view, ViewGroup parent) {
        ViewHolder viewHolder = null;
        final Person mContent = newsList.get(position);
        if (view == null) {
            viewHolder = new ViewHolder();
            view = LayoutInflater.from(mContext).inflate(R.layout.item_view, null);
            viewHolder.tvTitle = (TextView) view.findViewById(R.id.tv_city_name);
            view.setTag(viewHolder);
            viewHolder.tvLetter = (TextView) view.findViewById(R.id.tv_catagory);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }

        int section = getSectionForPosition(position);

        if (position == getPositionForSection(section)) {
            viewHolder.tvLetter.setVisibility(View.VISIBLE);
            viewHolder.tvLetter.setText(mContent.getSortLetters());
        } else {
            viewHolder.tvLetter.setVisibility(View.GONE);
        }

        viewHolder.tvTitle.setText(this.newsList.get(position).getName());
        return view;

    }


    private class ViewHolder {
        TextView tvLetter;
        TextView tvTitle;
    }

    public int getSectionForPosition(int position) {
        return newsList.get(position).getName().charAt(0);
    }

    public int getPositionForSection(int section) {

        for (int i = 0; i < getCount(); i++) {
            if(newsList.get(i).getSortLetters()!=null) {
                String sortStr = newsList.get(i).getSortLetters();
                char firstChar = sortStr.toUpperCase().charAt(0);
                if (firstChar == section) {
                    return i;
                }
            }
        }
        return -1;
    }

    @Override
    public Object[] getSections() {
        return null;
    }
}
